<?php

namespace App\Kuafu\Common\Service;

use GuzzleHttp\Client;
use GuzzleHttp\Exception\GuzzleException;
use Illuminate\Support\Str;
use Intervention\Image\Facades\Image;
use Kuafu\File\FileUtil;
use OSS\Core\OssException;

class ImageGenerationService
{
    const TYPE_PRICE_TAG       = 1; //价格标签
    const FILE_NAME_PREFIX     = 'kuafu_price_tag_image';
    const PRICE_TAG_FONT       = 'b4/c7/92fbc7167140164dc22ed708ee44eb8f013e4bd2ae28ef10235c2cd011f5.TTF'; // 尔雅新大黑
    const PRICE_TAG_PRICE_FONT = 'cd/fd/af7dbadaccdef6186cf806f50681016398065f97cd0dcadcb3a5398a502a.TTF'; // OPPOSans
    const PRICE_TAG_IMAGE      = 'a2/05/8bd76a36da89c79154eb1e8b5e5e949fe0b3cd9d5c179855dcff0a619e36.jpeg'; // 价签底板
    const FIRST_INSTRUCTION    = 'f2/17/98fdb5413682035cfafb3f1685dc66e3095436b2f3f7627924958b9449c5.png'; // PDF首页说明

    const TYPE_PATH = [
        self::TYPE_PRICE_TAG => self::FILE_NAME_PREFIX,
    ];

    /**
     * 制作价签
     * @param string $name 商品名称
     * @param string $price 价格
     * @return string
     */
    public static function generatePriceTag(string $name, string $price): string
    {
        $nameCount = mb_strlen($name);
        if ($nameCount <= 7) {
            $nameFontSize = 158;
        } elseif ($nameCount == 8) {
            $nameFontSize = 146;
        } else {
            $name = mb_substr($name, 0, 10);
            $nameFontSize = 116;
        }

        static::preparePriceTagResource();

        $img = Image::make(static::tempFileName('priceTag.png'));
        $img->text($name, 638, 125, function ($font) use ($nameFontSize) {
            $font->file(static::tempFileName('priceTagFont.ttf'));
            $font->size($nameFontSize);
            $font->color('#FFFFFF');
            $font->align('center');
            $font->valign('middle');
        })->text($price, 638, 325, function ($font) {
            $font->file(static::tempFileName('priceTagPriceFont.ttf'));
            $font->size(76);
            $font->color('#231815');
            $font->align('center');
            $font->valign('middle');
        });
        $saveFile = sys_get_temp_dir() . '/' . static::FILE_NAME_PREFIX . '/' . Str::random(10) . '.png';
        $img->save($saveFile);

        return $saveFile;
    }

    /**
     * 固定的文件在本地的临时地址
     * @param $name
     * @param int $type 证书类型
     * @return string
     */
    protected static function tempFileName($name, int $type = self::TYPE_PRICE_TAG): string
    {
        $path = self::TYPE_PATH[$type] ?? '';

        return sys_get_temp_dir() . '/' . $path . '/' . $name;
    }

    /**
     * 获取文件
     * @param $name
     * @param int $type
     * @return string
     */
    public static function getFile($name, int $type = self::TYPE_PRICE_TAG): string
    {
        $path = self::TYPE_PATH[$type] ?? '';

        return sys_get_temp_dir() . '/' . $path . '/' . $name;
    }

    /**
     * 下载oss文件到本地
     * @param string $url
     * @param string $localPath
     * @throws GuzzleException
     */
    protected static function downloadFile(string $url, string $localPath)
    {
        @unlink($localPath);
        // file_put_contents($localPath, file_get_contents(FileUtil::domain() . '/' . $url));
        (new Client())->get('https://kf-file.oss-cn-hangzhou-internal.aliyuncs.com/' . $url, ['http_errors' => false, 'sink' => $localPath]);
    }


    protected static function preparePriceTagResource()
    {
        if (!is_dir(sys_get_temp_dir() . '/' . static::FILE_NAME_PREFIX)) {
            @unlink(sys_get_temp_dir() . '/' . static::FILE_NAME_PREFIX);
            mkdir(sys_get_temp_dir() . '/' . static::FILE_NAME_PREFIX, 0777, true);
        }
        if (!static::checkSha256('priceTagFont.ttf', static::PRICE_TAG_FONT)) {
            static::downloadFile(static::PRICE_TAG_FONT, static::tempFileName('priceTagFont.ttf'));
        }
        if (!static::checkSha256('priceTagPriceFont.ttf', static::PRICE_TAG_PRICE_FONT)) {
            static::downloadFile(static::PRICE_TAG_PRICE_FONT, static::tempFileName('priceTagPriceFont.ttf'));
        }
        if (!static::checkSha256('priceTag.png', static::PRICE_TAG_IMAGE)) {
            static::downloadFile(static::PRICE_TAG_IMAGE, static::tempFileName('priceTag.png'));
        }
        if (!static::checkSha256('firstInstruction.png', static::FIRST_INSTRUCTION)) {
            static::downloadFile(static::FIRST_INSTRUCTION, static::tempFileName('firstInstruction.png'));
        }
    }

    /**
     * 检查文件指纹
     * @param $name
     * @param $url
     * @param int $type
     * @return bool
     */
    protected static function checkSha256($name, $url, int $type = self::TYPE_PRICE_TAG): bool
    {
        $tempFilename = static::tempFileName($name, $type);
        if (!is_readable($tempFilename)) {
            return false;
        }
        $sha256 = substr(str_replace('/', '', $url), 0, 64);
        if ($sha256 != hash_file('sha256', $tempFilename)) {
            return false;
        }
        return true;
    }

}